var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');

var app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));

var Card=require('./db').Card;
// 渲染页面
app.get('/cards',function(req,res){
  Card.find().then(function(cards){
    res.json({
      code:1,
      data:cards.map(function(item){
        var k=item.toObject();
        k.id=item._id.toString();
        delete k._id;
        return k;
      })
    })
  })
})
// 增
app.post('/card',function(req,res){
  Card(req.body).save().then(function(){
    res.json({
      code:1,
      msg:'保存数据成功'
    })
  })
})
//删
app.delete('/card/:id',function(req,res){
  Card.findByIdAndRemove(req.params.id).then(function(){
    res.json({
      code:1,
      msg:'删除数据成功'
    })
  })
})
// 找
app.get('/card/:id',function(req,res){
  Card.findById(req.params.id).then(function(card){
    var k=card.toObject();
    k.id=card._id.toString();
    delete k._id;
    res.json({
      code:1,
      data:k
    })
  })
})
//改
app.put('/card/:id',function(req,res){
  console.log(req.body);
  Card.findByIdAndUpdate(req.params.id,req.body).then(function(){
    res.json({
      code:1,
      msg:'修改成功'
    })
  })
})
app.listen(3000,function(){
  console.log('server on 3000...')
})
